<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="问题名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="问题名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="题目名称" prop="title"/>
        <el-table-column label="题目模式" prop="mode"/>
        <el-table-column label="题目类型" prop="typeText"/>
        <el-table-column label="图片文件" prop="imgFileName">
          <template slot-scope="scope">
            <a @click="showImg(scope.row.imgFileUrl)" style="color:rgb(7, 61, 238); cursor:pointer;">{{scope.row.imgFileName}}</a>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作"  min-width="400" width="400">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              v-show="scope.row.mode == 'QUESTION'"
              @click="openOptionsDialog(scope.row)"
            ><i class="el-icon-set-up"></i> 配置选项</el-button>
            <el-button
              type="success"
              size="small"
              link
              @click="openUploadDialog(scope.row.id)"
            ><i class="el-icon-edit"></i> 上传图片</el-button>
            <el-button
              type="warning"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            ><i class="el-icon-edit"></i> 编辑</el-button>
            <!-- <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            ><i class="el-icon-delete"></i> 删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      :visible.sync="uploadDialogVisible"
      title="上传图片"
      width="300px">
      <el-upload
        width="400"
        class="upload-dialog"
        ref="uploadImg"
        :action="imgUploadAction"
        :show-file-list="false"
        :on-change="submitImgUpload"
        :on-success="uploadFileSuccess"
        :headers="headers"
        :auto-upload="false">
        <el-button slot="trigger" style="margin-left: 5px" type="success">上传题目图片</el-button>
      </el-upload>
    </el-dialog>

    <el-dialog
      :visible.sync="showDialogVisible"
      title="查看图片"
      width="900px">
      <el-image
      style="width: 900px; height: 650px"
      :src="imgFileUrl"
      fit="contain"></el-image>
    </el-dialog>

    <!-- 问题表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="500px"
      :before-close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="问题名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入问题名称" />
        </el-form-item>
        <el-form-item label="问题模式" prop="mode">
          <el-radio-group v-model="formData.mode">
            <el-radio label="QUESTION">题目</el-radio>
            <el-radio label="PAGE">页描述</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述信息" prop="content" v-show="formData.mode == 'PAGE'">
          <el-input v-model="formData.content" type="textarea" :autosize="{ minRows: 8}" placeholder="请输入页描述信息" />
        </el-form-item>
        <el-form-item label="问题类型" prop="type" v-show="formData.mode == 'QUESTION'">
          <el-radio-group v-model="formData.type">
            <el-radio label="EXCLUSIVE_CHOICE">单选</el-radio>
            <el-radio label="MULTIPLE_CHOICE">多选</el-radio>
            <el-radio label="TEXTAREA">填空</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 配置选项弹窗  -->
    <el-dialog
      :visible.sync="optionsDialogVisible"
      :title="'【' + checkedQuestion.title + '】选项配置'"
      width="900px"
    >
      <el-scrollbar v-loading="loading" max-height="600px">
        <el-form
          ref="userFormRef1"
          :model="details"
          label-width="100px">
          <el-form-item label="问题名称" prop="title">
            <el-input v-model="details.title" disabled/>
          </el-form-item>

          <el-form-item label="问题类型" prop="type">
            <el-radio-group v-model="details.type" disabled>
              <el-radio label="EXCLUSIVE_CHOICE">单选</el-radio>
              <el-radio label="MULTIPLE_CHOICE">多选</el-radio>
              <el-radio label="TEXTAREA">填空</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="问题选项" prop="options">
            <el-table
              :data="details.options" :show-header="false" style="width: 90%; margin-left: 5%; margin-right: 5%;">
              <el-table-column label="" width="55" prop="dataIndex"/>
              <el-table-column prop="title" label=""></el-table-column>
              <el-table-column fixed="right" label="操作"  min-width="240" width="240">
                <template #default="scope">
                  <el-tag type="info" style="cursor: pointer; margin-left: 10px;" @click="upMove(scope)">上移</el-tag>
                  <el-tag type="info" style="cursor: pointer; margin-left: 10px;" @click="downMove(scope)">下移</el-tag>
                  <el-tag type="danger" style="cursor: pointer;margin-left: 10px;" @click="delOption(scope.row.id)">删除</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <el-button v-if="details.options && details.options.length != 0" type="primary" size="small" link
          style="float: right; margin-right: 5%; margin-top: 5px; margin-bottom: 5px;" @click="sortOptionList()">更新排序</el-button>

        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="optionList.filter(data => !optionSearchParam || data.title.toLowerCase().includes(optionSearchParam.toLowerCase()))"
          highlight-current-row
          border
          style="margin-top: 20px;"
        >
          <el-table-column label="选项标题" prop="title"/>
          <el-table-column label="创建时间" prop="createTimeText"/>
          <el-table-column
            align="right">
            <template slot="header" slot-scope="scope">
              <el-input
                v-model="optionSearchParam"
                size="mini"
                placeholder="输入关键字搜索"/>
            </template>
            <template slot-scope="scope">
              <el-button :disabled="!scope.row.selectButton"
                type="warning"
                size="small"
                link
                @click="addOption(scope.row.id)"
              ><i class="el-icon-edit"></i> 添加至问题</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="optionsDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Session } from '@/utils/storage';
import optionApi from '@/api/aliyun/questionnaire/option'
import questionApi from '@/api/aliyun/questionnaire/question'
import { formatDate } from '@/utils/formatTime'
export default {
	name: 'userIndex',
	data() {
		return {
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      optionsDialogVisible: false,
      optionList: [],
      checkedQuestion: {},
      dialog: {},
      formData: {},
      rules: {},

      typeMap: {
        EXCLUSIVE_CHOICE: '单选',
        MULTIPLE_CHOICE: '多选',
        TEXTAREA: '填空',
      },
      details: {},
      optionSearchParam: '',

      imgUploadAction: '',
      headers: {},
      uploadDialogVisible: false,
      questionId: '',

      showDialogVisible: false,
      imgFileUrl: '',
		};
	},
	mounted() {
		this.headers = {
			Authorization: 'Bearer ' + localStorage.getItem('token'),
		};
	},
  methods: {
    showImg (imgFileUrl) {
      this.imgFileUrl = imgFileUrl;
      this.showDialogVisible = true;
    },
    openUploadDialog (questionId) {
      this.questionId = questionId;
      this.uploadDialogVisible = true;
      
      if (process.env.NODE_ENV === 'production') {
        this.imgUploadAction = 'https://w66h994817.zicp.fun/platform/aliyun-api/question/upload-image/' + questionId;
      } else {
        this.imgUploadAction = process.env.VUE_APP_FILE_API_PREV + '/question/upload-image/' + questionId;
      }
    },
    submitImgUpload () {
      this.$refs.uploadImg.submit();
    },
    uploadFileSuccess () {
      this.uploadDialogVisible = false;
      this.$message({ message: '题目图片上传成功！', type: 'success' });
    },
    addOption(optionId) {
      let questionId = this.checkedQuestion.id;
      let optionIds = [optionId];
      questionApi.configOptions(questionId, optionIds).then((res) => {
        this.$message({message: '问题选项添加成功！', type: 'success'});
        questionApi.detail(questionId).then((res) => {
          this.details = res.data;
        });
      });
    },
    delOption (optionId) {
      let questionId = this.checkedQuestion.id;
      let optionIds = [optionId];
      questionApi.deleteOptions(questionId, optionIds).then((res) => {
        this.$message({message: '问题选项删除成功！', type: 'success'});
        questionApi.detail(questionId).then((res) => {
          this.details = res.data;
        });
      });
    },
    downMove (o) {
      let index = o.$index;
      let options = this.details.options;
      if (index == options.length - 1) {
        this.$message.error('当前选项已经是最后一个，不能移动！');
        return;
      }
      options.splice(index, 1, ...options.splice(index + 1, 1, options[index]));
      this.$set(this.details, 'options', options);
    },
    upMove (o) {
      let index = o.$index;
      if (index == 0) {
        this.$message.error('当前选项已经是第一个，不能移动！');
        return;
      }
      let options = this.details.options;
      options.splice(index - 1, 1, ...options.splice(index, 1, options[index - 1]))
      this.$set(this.details, 'options', options);
    },
    sortOptionList () {
      let questionId = this.checkedQuestion.id;
      let options = this.details.options;
      let optionIds = [];
      options.forEach((v) => {
        optionIds.push(v.id);
      });
      questionApi.sortOptions(questionId, optionIds).then((res) => {
        this.$message({message: '问题选项排序成功！', type: 'success'});
        questionApi.detail(questionId).then((res) => {
          this.details = res.data;
        });
      });
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      questionApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        let index = 1;
        data.content.forEach(v => {
          v.typeText = that.typeMap[v.type];
          v.dataIndex = index++;
        });
        this.dataList = data.content;
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        questionApi.update(this.formData).then((res) => {
          this.$message({message: '问题更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        questionApi.add(this.formData).then((res) => {
          this.$message({message: '问题添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },

    openOptionsDialog(row) {
      this.optionsDialogVisible = true;
      this.checkedQuestion = row;
      let dIndex = 1;
      questionApi.detail(row.id).then((res) => {
        res.data.options.forEach(d => {
          d.dataIndex = dIndex++;
        })
        this.details = res.data;
        let questionIds = [];
        res.data.options.forEach((t) => {
          questionIds.push(t.id);
        });
        optionApi.list().then((res1) => {
          this.optionList = res1.data;
          this.optionList.forEach(v => {
            v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
            if (questionIds.indexOf(v.id) != -1) {
              v.selectButton = false;
            } else {
              v.selectButton = true;
            }
          });
        });
      });
      
    },
    closeRoleDialog() {
      this.optionsDialogVisible = false;
      this.optionList = [];
    },

    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      if (id) {
        this.$set(this.dialog, 'title', '编辑问题');
        questionApi.get(id).then((res) => {
          let data = res.data;
          that.formData = data;

        });
      } else {
        this.$set(this.dialog, 'title', '新增问题');
        that.formData = {};
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (id) {
          questionApi.delete(id).then((res) => {
            this.$message({message: '问题删除成功！', type: 'success'});
            this.handleQuery();
          });
        } else {
          this.$message.error('暂不支持批量删除问题！');
        }
      }).catch(() => {});
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>